package com.qing.shirodemo.config;

import at.pollux.thymeleaf.shiro.dialect.ShiroDialect;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.LinkedHashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {


    @Bean
    public ShiroFilterFactoryBean shiroFilterFactoryBean(@Qualifier("defaultWebSecurityManager") DefaultWebSecurityManager defaultWebSecurityManager){
        ShiroFilterFactoryBean bean=new ShiroFilterFactoryBean();
        //设置安全管理
        bean.setSecurityManager(defaultWebSecurityManager);
        //添加shiro的内置过滤器
        /*
        * anon: 无需认证就可以访问
        * authc：必须认证了才能访问
        * user: 必须拥有 记住我 功能才能用
        * perms: 拥有某个资源的权限才能用
        * role: 拥有某个角色权限才能访问
        * */
        Map<String,String> filter=new LinkedHashMap<>();
//        filter.put("/user/add","anon");
//        filter.put("/user/update","authc");

        //授权，正常情况下，没有授权，会跳转到未授权页面
        filter.put("/user/add","perms[user:add]");
        filter.put("/user/update","perms[user:update]");
        //拦截
        filter.put("/user/*","authc");
        filter.put("/index","authc");

        bean.setFilterChainDefinitionMap(filter);
        //设置登录的请求
        bean.setLoginUrl("/tologin");
        //设置未授权的请求
        bean.setUnauthorizedUrl("/unauthorized");
        return  bean;
    }

    @Bean
    public DefaultWebSecurityManager defaultWebSecurityManager(@Qualifier("userRealm") UserRealm userRealm){
        DefaultWebSecurityManager securityManager=new DefaultWebSecurityManager();
        securityManager.setRealm(userRealm);
        return  securityManager;
    }

    @Bean(name = "userRealm")
    public UserRealm userRealm(){
        return  new UserRealm();
    }


    //整合 shiro thymelaf
    @Bean
    public ShiroDialect shiroDialect(){
        return new ShiroDialect();
    }
}
